/*
 * Copyright (C) 2020 Graylog, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Server Side Public License, version 1,
 * as published by MongoDB, Inc.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * Server Side Public License for more details.
 *
 * You should have received a copy of the Server Side Public License
 * along with this program. If not, see
 * <http://www.mongodb.com/licensing/server-side-public-license>.
 */
package org.graylog.plugins.views.search.db;

import name.falgout.jeffrey.testing.junit.guice.GuiceExtension;
import name.falgout.jeffrey.testing.junit.guice.IncludeModule;
import name.falgout.jeffrey.testing.junit.guice.IncludeModules;
import org.graylog.plugins.views.search.SearchRequirements;
import org.graylog.plugins.views.search.searchfilters.db.IgnoreSearchFilters;
import org.graylog.plugins.views.search.views.ViewSummaryService;
import org.graylog.testing.inject.InputConfigurationModule;
import org.graylog.testing.inject.TestPasswordSecretModule;
import org.graylog.testing.mongodb.MongoDBExtension;
import org.graylog.testing.mongodb.MongoDBFixtures;
import org.graylog2.database.MongoCollections;
import org.graylog2.shared.bindings.ObjectMapperModule;
import org.graylog2.shared.bindings.ValidatorModule;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@ExtendWith(MongoDBExtension.class)
@ExtendWith(GuiceExtension.class)
@IncludeModules({
        @IncludeModule(InputConfigurationModule.class),
        @IncludeModule(ObjectMapperModule.class),
        @IncludeModule(ValidatorModule.class),
        @IncludeModule(TestPasswordSecretModule.class)
})
public class SearchesCleanUpJobWithDBServicesTest {

    private SearchesCleanUpJob searchesCleanUpJob;
    private SearchDbService searchDbService;

    static class TestViewService extends ViewSummaryService {
        TestViewService(MongoCollections mongoCollections) {
            super(mongoCollections);
        }
    }

    @BeforeEach
    public void setup(MongoCollections mongoCollections) {
        DateTimeUtils.setCurrentMillisFixed(DateTime.parse("2018-07-03T13:37:42.000Z").getMillis());


        final ViewSummaryService viewService = new TestViewService(mongoCollections);
        this.searchDbService = spy(
                new SearchDbService(
                        mongoCollections,
                        dto -> new SearchRequirements(Collections.emptySet(), dto),
                        new IgnoreSearchFilters()
                )
        );
        this.searchesCleanUpJob = new SearchesCleanUpJob(viewService, searchDbService, Duration.standardDays(4),
                new HashMap<>(), new HashSet<>());
    }

    @AfterEach
    public void cleanup() throws Exception {
        DateTimeUtils.setCurrentMillisSystem();
    }

    @Test
    public void testForAllEmpty() {
        this.searchesCleanUpJob.doRun();

        verify(searchDbService, never()).delete(any());
    }

    @Test
    @MongoDBFixtures("mixedExpiredAndNonExpiredSearches.json")
    public void testMixedExpiredAndNonExpiredSearches() {
        this.searchesCleanUpJob.doRun();

        final ArgumentCaptor<String> idCaptor = ArgumentCaptor.forClass(String.class);
        verify(searchDbService, times(1)).delete(idCaptor.capture());

        assertThat(idCaptor.getAllValues()).containsExactly("5b3b44ca77196aa4679e4da0");
    }

    @Test
    @MongoDBFixtures("mixedExpiredNonExpiredReferencedAndNonReferencedSearches.json")
    public void testMixedExpiredNonExpiredReferencedAndNonReferencedSearches() {
        this.searchesCleanUpJob.doRun();

        final ArgumentCaptor<String> idCaptor = ArgumentCaptor.forClass(String.class);
        verify(searchDbService, times(2)).delete(idCaptor.capture());

        assertThat(idCaptor.getAllValues()).containsExactly("5b3b44ca77196aa4679e4da1", "5b3b44ca77196aa4679e4da2");
    }
}
